package com.dsg.controller.bank;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.DateUtils;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.dao.account.DsgAccountCardMapper;
import com.dsg.entity.account.DsgAccountSetting;
import com.dsg.entity.bank.DsgBankDetail;
import com.dsg.entity.bank.DsgBankDetailTxtATPVo;
import com.dsg.entity.bank.DsgBankRecord;
import com.dsg.entity.bank.DsgBankRecordTxtATPVo;
import com.dsg.entity.model.bank.DsgBankDetailModel;
import com.dsg.entity.system.DsgSysFile;
import com.dsg.service.account.IDsgAccountSettingService;
import com.dsg.service.account.IDsgAccountTradeService;
import com.dsg.service.bank.IDsgBankDetailService;
import com.dsg.service.bank.IDsgBankRecordService;
import com.dsg.service.bank.IDsgBankResultService;
import com.dsg.service.system.IDsgSysFileService;
import com.dsg.support.LeveldbAccess;
import com.dsg.util.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 銀行往來過數檔案 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-07-12
 */
@RestController
@RequestMapping("/bank/dsgBankRecord")
public class DsgBankRecordController extends BaseController {

    @Autowired
    private IDsgBankRecordService dsgBankRecordService;
    @Autowired
    private IDsgBankDetailService dsgBankDetailService;
    @Autowired
    private IDsgBankResultService dsgBankResultService;
    @Autowired
    private IDsgAccountTradeService dsgAccountTradeService;
    @Autowired
    private DsgAccountCardMapper dsgAccountCardMapper;
    @Autowired
    private IDsgAccountSettingService dsgAccountSettingService;
    @Autowired
    private IDsgSysFileService dsgSysFileService;
    @Autowired
    private LeveldbAccess leveldbAccess;

    /**
     * 查询列表（分页）
     *
     * @param dsgBankRecord
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation("查询列表（分页）")
    public AjaxResult list(DsgBankRecord dsgBankRecord) {
        // 分页
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        if (StringUtil.isEmpty(sort)) {
            orderItemList.add(new OrderItem().setColumn("CREATE_TIME").setAsc(false));
            page.setOrders(orderItemList);
        }
//        dsgBankRecord.setEntCode(SingletonLoginUtils.getSystemEntCode());
        page = dsgBankRecordService.selectByList(page, dsgBankRecord);
        // 格式要返回的数据
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, page.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }

    /**
     * 批量删除
     *
     * @return
     */
    @DeleteMapping(value = "/delete")
    @ApiOperation("批量删除")
    public AjaxResult delete(@ApiParam(value = "id以，号分隔", name = "idList", required = true) @RequestParam String idList) {
        dsgBankRecordService.batchDelete(idList);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    /**
     * 下載
     *
     * @return
     */
    @GetMapping(value = "{id}/downloadFile")
    @ApiOperation("下載")
    public void downloadFile(@ApiParam(value = "id", name = "id", required = true) @PathVariable String id,
                             HttpServletResponse response) throws Exception {
        DsgBankRecord dsgBankRecord = dsgBankRecordService.getById(id);
        if (dsgBankRecord != null) {
            //查詢銀行
            QueryWrapper<DsgAccountSetting> dasQueryWrapper = new QueryWrapper<>();
            dasQueryWrapper.eq("ACCOUNT_NO ", dsgBankRecord.getAccountNo());
            DsgAccountSetting dsgAccountSetting = dsgAccountSettingService.getOne(dasQueryWrapper);
            if (dsgAccountSetting != null) {
                switch (dsgAccountSetting.getPayMethod()) {
                    case Constant.PAY_TYPE_CDC:
                        switch (dsgAccountSetting.getBankId()) {
                            case "Bea":
                                dsgBankRecordService.downloadBea(response, dsgBankRecord);
                                break;
                            case "Dbs":
                                break;
                            case "HangSeng":
                                break;
                            case "Ocbc":
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        List<DsgBankRecordTxtATPVo> dsgBankRecordTxtATPList = new ArrayList<>();
                        DsgBankRecordTxtATPVo dsgBankRecordTxtATP = new DsgBankRecordTxtATPVo();
                        BeanUtils.copyProperties(dsgBankRecord, dsgBankRecordTxtATP);
                        dsgBankRecordTxtATPList.add(dsgBankRecordTxtATP);
                        ExportTextUtil etu = new ExportTextUtil();
                        etu.write(DsgBankRecordTxtATPVo.class, dsgBankRecordTxtATPList);
                        DsgBankDetail dsgBankDetail = new DsgBankDetail();
                        dsgBankDetail.setRecordId(id);
                        Page<DsgBankDetail> page = new Page<>();
                        int currentPage = 0;
                        page.setSize(EasyExcelUtils.PER_WRITE_ROW_COUNT);
                        // 排序
                        List<OrderItem> orderItemList = new ArrayList<>();
                        orderItemList.add(new OrderItem().setColumn("CREATE_TIME").setAsc(false));
                        page.setOrders(orderItemList);
                        List<DsgBankDetail> dsgBankDetailList;
                        do {
                            page.setCurrent(++currentPage);
                            dsgBankDetailList = dsgBankDetailService.selectByDetailList(page, dsgBankDetail).getRecords();
                            etu.write(DsgBankDetailTxtATPVo.class, dsgBankDetailList);
                        } while (CollectionUtil.isNotEmpty(dsgBankDetailList) && dsgBankDetailList.size() == EasyExcelUtils.PER_WRITE_ROW_COUNT);
                        String fileName = DateUtils.getDateTime();
                        etu.writeToTxt(response, fileName);
                        break;
                }
            }
        } else {
            throw new RRException("銀行賬號不存在！");
        }
    }

    /**
     * 上載
     *
     * @param id
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value = "{id}/importExcel")
    @ApiOperation("上載")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importExcel(@ApiParam(value = "id", name = "id", required = true) @PathVariable String id,
                                  @ApiParam(value = "file", name = "file", required = true) @RequestParam("file") MultipartFile file) throws Exception {
        File excelFile = ExcelIteratorReader.multipartToFile(file);
        //保存文件
        dsgSysFileService.saveFile(new DsgSysFile(), excelFile, id, "xlsx");
        EasyExcel.read(file.getInputStream(), DsgBankDetailModel.class, new UploadDsgBankDetail(id, dsgBankRecordService,
                dsgBankDetailService, dsgBankResultService, dsgAccountCardMapper, dsgAccountTradeService)).sheet(0).headRowNumber(3).doRead();
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    /**
     * 查询匯總分組列表（分頁）
     *
     * @param dsgBankRecord
     * @return
     */
    @GetMapping(value = "/listGroup")
    @ApiOperation("查询匯總分組列表（分頁）")
    public AjaxResult listGroup(DsgBankRecord dsgBankRecord) {
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        if (StringUtil.isEmpty(sort)) {
            orderItemList.add(new OrderItem().setColumn("createDate").setAsc(false));
            page.setOrders(orderItemList);
        }
        dsgBankRecord.setEntCode(SingletonLoginUtils.getSystemEntCode());
        page = dsgBankRecordService.selectByGroupList(page, dsgBankRecord);
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, page.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }
}
